from typing import List

from ninja_extra import api_controller, route
from ninja_extra.permissions import IsAuthenticated
from ninja_jwt.authentication import JWTAuth

from meiduo_mall.base.schemas import Message
from .models import Area
from .schema import AreaSchema, AreaSubsSchema


@api_controller(tags=['地址管理'], auth=JWTAuth(), permissions=[IsAuthenticated])
# 　TODO:缓存到redis未完成
class AreaController:
    @route.get('/areas/', summary='查询所有省', response={200: List[AreaSchema], 400: Message})
    def areas(self):
        try:
            qs = Area.objects.filter(parent=None)
        except Exception as e:
            return 400, {'msg': f'网络异常，请刷新,{e}'}
        return 200, qs

    @route.get('/areas/{id}/', summary='查询省详细', response={200: AreaSubsSchema, 400: Message})
    def area(self, aid: int):
        try:
            qs = Area.objects.get(id=aid)
        except Area.DoesNotExist:
            return 400, {'msg': '查询参数错误，请刷新'}
        return 200, qs
